import json
import random
import re

from django.contrib.auth import login, authenticate, logout
# Create your views here.
from django.http import JsonResponse, HttpResponse
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User
from ihome.utils.views import LoginRequiredJSONMixin
from .libs.captcha.captcha import captcha
import logging
logger = logging.getLogger('django')




class ImageVerifyView(View):

    def get(self, request):

        cur = request.GET.get('cur')
        pre = request.GET.get('pre')

        if not all([cur]):
            return JsonResponse({'code': 4002, 'errmsg': '缺少必传参数'})

        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection('verify_code')

        if pre:
            redis_conn.delete('img_%s' % pre)

        redis_conn.setex('img_%s' % cur, 300, text)

        return HttpResponse(image, content_type='image/jpg')


class SMSVerifyView(View):

    def post(self, request):

        json_dict = json.loads(request.body.decode())

        mobile = json_dict.get('mobile')
        id = json_dict.get('id')
        text_client = json_dict.get('text')

        redis_conn = get_redis_connection('verify_code')
        flag = redis_conn.get('sms_flag_%s' % mobile)

        if flag:
            return JsonResponse({"errno": 4201, 'errmsg': '短信国语频繁'})

        if not all([mobile, id, text_client]):
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        if not re.match('1[3-9]\d{9}', mobile):
            return JsonResponse({'errno': 4004, 'errmsg': 'mobile数据有误'})


        text_server = redis_conn.get('img_%s' % id)

        if not text_server:
            return JsonResponse({'errno': 4001, 'errmsg': '图形验证码已过期'})

        if text_client.lower() != text_server.decode().lower():
            return JsonResponse({'errno': 4004, 'errmsg': '图形验证码有误'})

        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        pl = redis_conn.pipeline()

        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        pl.setex('sms_flag_%s' % mobile, 60, 1)

        pl.execute()

        # send_sms_code.delay(mobile, sms_code)

        return JsonResponse({"errno": "0","errmsg": "发送成功"})


class RegisterView(View):

    def post(self, request):

        json_dict = json.loads(request.body.decode())

        mobile = json_dict.get('mobile')
        sms_code_client = json_dict.get('phonecode')
        password = json_dict.get('password')

        if not all([mobile, sms_code_client, password]):
            return JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 4103, 'errmsg': 'mobile格式有误'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 4103, 'errmsg': 'password格式有误'})

        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_code_%s' % mobile)

        if not sms_code_server:
            return JsonResponse({'errno': 4002, 'errmsg': '验证码已过期'})

        if sms_code_client != sms_code_server.decode():
            return JsonResponse({'errno': 4103, 'errmsg': '短信验证码输入错误'})

        try:
            user = User.objects.create_user(username=mobile,
                                            mobile=mobile,
                                            password=password)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库写入失败'})

        login(request, user)

        return JsonResponse({"errno": "0", "errmsg": "注册成功"})


class LoginView(View):

    def post(self, request):

        json_dict = json.loads(request.body.decode())

        account = json_dict.get('mobile')
        password = json_dict.get('password')

        if not all([account, password]):
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', account):
            return JsonResponse({'errno': 4103, 'errmsg': 'mobile格式有误'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 4103, 'errmsg': 'password格式有误'})

        if re.match(r'^1[3-9]\d{9}$', account):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        try:
            user = authenticate(request, username=account, password=password)
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        if user == None:
            return JsonResponse({'errno': 4103, 'errmsg': '用户名或密码错误'})

        login(request, user)

        return JsonResponse({"errno": "0", "errmsg": "登录成功"})


    def get(self, request):
        """

        :param request:
        :return:
        // 已登录：
        {
            "errno": "0",
            "errmsg": "已登录",
            "data": {
                "name": "用户名"
            }
        }
        // 未登录：
        {
            "errno": "4101",
            "errmsg": "未登录"
        }
        """
        if request.user.is_authenticated:
            return JsonResponse({"errno": "0",
                                 "errmsg": "已登录",
                                 "data": {'user_id': request.user.id,
                                          "name": request.user.username
                                 }
            })

        return JsonResponse({"errno": "4101",
                             "errmsg": "未登录"})


    def delete(self, request):

        logout(request)

        response = JsonResponse({"errno": "0",
                                 "errmsg": "已登出"
                                })


        return response


class UserInfoView(LoginRequiredJSONMixin, View):

    def get(self, request):
        """

        :param reqest:
        :return:
            {
                "data": {
                    "avatar": "http://oyucyko3w.bkt.clouddn.com/FmWZRObXNX6TdC8D688AjmDAoVrS",
                    "create_time": "2017-11-07 01:10:21",
                    "mobile": "18599998888",
                    "name": "哈哈哈哈哈哈",
                    "user_id": 1
                },
                "errmsg": "OK",
                "errno": "0"
            }
        """

        user = request.user

        user_data = {
            "avatar_url": 'http://www.ihome.site:8080/img/1.png',
            "create_time": user.date_joined,
            "mobile": user.mobile,
            "name": user.username,
            "user_id": user.id
        }

        return JsonResponse({
            "data": user_data,
            "errmsg": "OK",
            "errno": 0
        })

class UpdateUsernameView(LoginRequiredJSONMixin, View):

    def put(self, request):

        json_dict = json.loads(request.body.decode())

        new_name = json_dict.get('name')

        user = request.user

        if not new_name:
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        try:
            user.username = new_name
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库写入错误'})

        return JsonResponse({"errno": "0", "errmsg": "修改成功"})


def is_Chinese(word):
    for ch in word:
        if '\u4e00' <= ch <= '\u9fff':
            return True
    return False

class IDCardView(LoginRequiredJSONMixin, View):

    def post(self, request):
        """

        # ^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$
        :param request:
        :return:
        """
        json_dict = json.loads(request.body.decode())

        real_name =json_dict.get('real_name')
        id_card = json_dict.get('id_card')

        if not all([real_name, id_card]):
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        if not is_Chinese(real_name):
            return JsonResponse({'errno': 4103, 'errmsg': '姓名与身份证匹配失败'})

        if not re.match(r'^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',
                    id_card):
            return JsonResponse({'errno': 4103, 'errmsg': '姓名与身份证匹配失败'})

        try:
            user = request.user
            user.real_name=real_name
            user.id_card=id_card
            user.save()
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库写入错误'})

        return JsonResponse({"errno": 0, "errmsg": "认证信息保存成功"})

    def get(self, request):

        user = request.user

        try:
            real_name = user.real_name
            id_card = user.id_card
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})
        data = {'real_name': real_name,
                'id_card': id_card}

        # if all([real_name, id_card]):
        return JsonResponse({"errno": 0,
                        "errmsg": "查询认证信息",
                         'data': data})
